package com.itheima.listener;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.itheima.commons.model.mongo.RecommendVideo;
import com.itheima.commons.model.mongo.Video;
import com.itheima.dubbo.interfaces.VideoApi;
import jdk.nashorn.internal.ir.annotations.Reference;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;

@Component
@RocketMQMessageListener(topic = "tanhua-video",
        consumerGroup = "tanhua-video-consumer")
public class VideoMsgConsumer implements RocketMQListener<String> {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Reference
    private VideoApi videoApi;

    @Override
    public void onMessage(String msg) {
        try {
            // 解析消息体内容
            JSONObject jsonObject = JSONUtil.parseObj(msg);
            Long userId = jsonObject.getLong("userId");
            String videoId = jsonObject.getStr("videoId");
            Integer type = jsonObject.getInt("type");

            Video video = videoApi.queryVideoById(videoId);

            // 消费消息  :   怎么处理这个消息内容
            //1-发动态，2-点赞， 3-取消点赞，4-评论
            RecommendVideo recommendVideo = new RecommendVideo();
            recommendVideo.setUserId(userId);
            recommendVideo.setId(ObjectId.get());
            recommendVideo.setDate(System.currentTimeMillis());
            recommendVideo.setVideoId(video.getVid());

            // 根据操作类型去设置分数
            // -5分  5分删除掉  某个用户  某个小视频 总分
            switch (type) {
                case 1: {
                    recommendVideo.setScore(2d);
                    break;
                }
                case 2: {
                    recommendVideo.setScore(5d);
                    break;
                }
                case 3: {
                    recommendVideo.setScore(-5d);
                    break;
                }
                case 4: {
                    recommendVideo.setScore(10d);
                    break;
                }
                default: {
                    recommendVideo.setScore(0d);
                    break;
                }
            }

            this.mongoTemplate.save(recommendVideo);
        } catch (Exception e) {
            System.out.println("处理小视频消息失败~" + msg);
        }
    }
}
